package com.huiyun.project.im.server.biz.controller.sv;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.huiyun.project.common.core.domain.R;
import com.huiyun.project.common.core.util.fn.FunctionUtils;
import com.huiyun.project.im.common.auth.SecurityUtils;
import com.huiyun.project.im.common.auth.UserPrincipal;
import com.huiyun.project.im.consts.ImServerConst;
import com.huiyun.project.im.core.dto.ImFriendDto;
import com.huiyun.project.im.core.dto.ImGroupDto;
import com.huiyun.project.im.entity.ImUser;
import com.huiyun.project.im.core.service.IImFriendService;
import com.huiyun.project.im.core.service.IImGroupService;
import com.huiyun.project.im.core.service.IImUserService;
import org.jim.core.packets.pub.pojo.Group;
import org.jim.core.packets.pub.pojo.JimUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wf.jwtp.annotation.Inner;
import org.wf.jwtp.annotation.Logical;
import org.wf.jwtp.annotation.RequiresRoles;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("sv/user")
public class ImUserController {
    @Autowired
    private IImUserService userService;
    @Autowired
    private IImFriendService friendService;
    @Autowired
    private IImGroupService groupService;


    /**
     * token 获取用户信息
     *
     * @return
     */
    @RequestMapping("/getUserByToken")
    @RequiresRoles(value = {ImServerConst.API_TENANT_ROLE, ImServerConst.API_USER_ROLE}, logical = Logical.OR)
    public R getUserByToken() {
        return FunctionUtils.wrapper(() -> {
            UserPrincipal userPrincipal = SecurityUtils.getUserPrincipal();
            Assert.notNull(userPrincipal);
            JimUser.Builder builder = new JimUser.Builder();
            buildUser(builder, userPrincipal);
            //查询 friends
            List<ImFriendDto> friendList = friendService.findFriend(userPrincipal.getId());
            if (CollectionUtil.isNotEmpty(friendList)) {
                Group myFriend = Group.newBuilder().groupId("1").name("我的好友").build();
                myFriend.setUsers(buildUsers(friendList));
                builder.addFriend(myFriend);
            }
            //查询 groups
            List<ImGroupDto> groupList = groupService.findGroup(userPrincipal.getId());
            if (CollectionUtil.isNotEmpty(groupList)) {
                for (ImGroupDto dto : groupList) {
                    builder.addGroup(Group.newBuilder().groupId(dto.getImGroupId()).name(dto.getName()).build());
                }
            }
            return R.ok(builder.build());
        });
    }


    /**
     * 获取租户下的客服列表
     *
     * @return
     */
    @GetMapping("/getCsList")
    @Inner
    public R<List<ImUser>> getCsList(@RequestParam("imTenantId") String imTenantId, @RequestParam("agentOrgId") String userOrgId) {
        return FunctionUtils.wrapper(() -> R.ok(userService.getCsList(imTenantId, userOrgId)));
    }


    private void buildUser(JimUser.Builder builder, UserPrincipal userPrincipal) {
        String userId=userPrincipal.getId();
        if(userId.indexOf(":")>-1){
            userId=userId.split(":")[1];
        }
        builder.userId(userId)
                .username(userPrincipal.getUsername())
                .nick(userPrincipal.getNick())
                .imTenantId(userPrincipal.getImTenantId())
                .userOrgId(userPrincipal.getUserOrgId())
                .appGroupId(userPrincipal.getAppGroupId())
                .appId(userPrincipal.getAppId())
                .imSpId(userPrincipal.getImSpId())
                .type(userPrincipal.getType())
                .terminal(userPrincipal.getTerminal())
                .avatar(userPrincipal.getAvatar());
    }

    private List<JimUser> buildUsers(List<ImFriendDto> friendList) {
        Group myFriend = Group.newBuilder().groupId("1").name("我的好友").build();
        List<JimUser> myFriendGroupUsers = new ArrayList();
        JimUser user;
        for (ImFriendDto dto : friendList) {
            user = JimUser.newBuilder()
                    .username(dto.getUsername())
                    .nick(dto.getNick())
                    .avatar(dto.getAvatar())
                    .build();
            myFriendGroupUsers.add(user);
        }
        return myFriendGroupUsers;
    }

}
